//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.Collections
{
    class SingleItemDictionary<TValue>: IFrugalDictionary<TValue> where TValue: class
    {
        KeyValuePair<int, TValue> _entry = FrugalHelper.GetEmptyPair<TValue>();

        #region IFrugalDictionary<TValue> Members

        int IFrugalDictionary<TValue>.Count
        {
            get
            {
                if (FrugalHelper.IsSet(_entry.Key))
                    return 1;
                return 0;
            }
        }

        #endregion

        #region IFrugalDictionary<TValue> Members



        bool IFrugalDictionary<TValue>.Remove(int key)
        {
            if (key == _entry.Key)
            {
                _entry = FrugalHelper.GetEmptyPair<TValue>();
                return true;
            }
            return false;
        }

        IEnumerator<int> IFrugalDictionary<TValue>.GetEnumerator()
        {
            if (FrugalHelper.IsSet(_entry.Key))
                yield return _entry.Key;
        }

        #endregion
        public bool ContainsKey(int key)
        {
            TValue value;
            IFrugalDictionary<TValue> dic = this;
            return dic.TryGetValue(key, out value);
        }


        #region IFrugalDictionary<TValue> Members


        bool IFrugalDictionary<TValue>.TryGetValue(int key, out TValue value)
        {
            if (_entry.Key == key)
            {
                value = _entry.Value;
                return true;
            }
            value = default(TValue);
            return false;
        }

        #endregion

        #region IFrugalDictionary<TValue> Members


        IFrugalDictionary<TValue> IFrugalDictionary<TValue>.TryAddValue(int key, TValue value)
        {
#if DEBUG
            Contract.Requires(!this.ContainsKey(key));
#endif
            if (!FrugalHelper.IsSet(_entry.Key))
            {
                _entry = new KeyValuePair<int, TValue>(key, value);
                return null;
            }
            return new ThreeItemsDictionary<TValue>();
        }

        #endregion
    }
}
